package com.facedemo.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;

/**
 * 使用RenderScript将视频YUV流转换为BMP
 */
public class FastYUVtoRGB {
    private RenderScript rs;
    private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;
    private Type.Builder yuvType, rgbaType;
    private Allocation in, out;
    private long time = 0;

    private volatile static FastYUVtoRGB fastYUVtoRGB;

    public static FastYUVtoRGB getInstance() {
        if (null == fastYUVtoRGB) {
            synchronized (FastYUVtoRGB.class) {
                if (null == fastYUVtoRGB) {
                    fastYUVtoRGB = new FastYUVtoRGB();
                }
            }
        }
        return fastYUVtoRGB;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void initContext(Context context) {
        rs = RenderScript.create(context);
        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
    }

//    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
//    public FastYUVtoRGB(Context context) {
//        rs = RenderScript.create(context);
//        yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
//    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public Bitmap convertYUVtoRGB(byte[] yuvData, int width, int height) {
//        time = System.currentTimeMillis();
        if (yuvType == null) {
            yuvType = new Type.Builder(rs, Element.U8(rs)).setX(yuvData.length);
            in = Allocation.createTyped(rs, yuvType.create(), Allocation.USAGE_SCRIPT);

            rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
            out = Allocation.createTyped(rs, rgbaType.create(), Allocation.USAGE_SCRIPT);
        }
        in.copyFrom(yuvData);
        yuvToRgbIntrinsic.setInput(in);
        yuvToRgbIntrinsic.forEach(out);
        Bitmap bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        out.copyTo(bmpout);
//        Log.i("hww","convertYUVtoRGB  = "+(System.currentTimeMillis() - time));
        return bmpout;
    }
}